package nc

import (
	"fmt"

	"github.com/project-flogo/core/activity"
	"github.com/project-flogo/core/data/metadata"

	"gitee.com/shipnet/flogo-common/netclient"
)

func init() {
	_ = activity.Register(&Activity{}, New)
}

var activityMd = activity.ToMetadata(&Settings{}, &Input{}, &Output{})

// New create activity
func New(ctx activity.InitContext) (activity.Activity, error) {
	settings := Settings{}
	err := metadata.MapToStruct(ctx.Settings(), &settings, true)
	if err != nil {
		return nil, err
	}
	nsettings := netclient.Settings{
		Addr:              fmt.Sprintf("%s://%s:%s", settings.Network, settings.Host, settings.Port),
		MaxSize:           10,
		Timeout:           "300s",
		ConnectionDelay:   "0s",
		ReconnectInterval: "10s",
		Logger:            ctx.Logger(),
	}
	client, err := netclient.New(nsettings)
	if err != nil {
		return nil, err
	}
	act := &Activity{
		settings: settings,
		client:   client,
	}

	return act, nil
}

// Activity is an Activity that is used to reply/return via the trigger
// inputs : {method,uri,params}
// outputs: {result}
type Activity struct {
	settings Settings
	client   netclient.NetClient
}

// Metadata returns the activity's metadata
func (a *Activity) Metadata() *activity.Metadata {
	return activityMd
}

// Eval implements api.Activity.Eval - Invokes a REST Operation
func (a *Activity) Eval(ctx activity.Context) (bool, error) {
	input := Input{}
	err := ctx.GetInputObject(&input)
	if err != nil {
		return true, err
	}
	payload := input.Data
	if a.client != nil {
		werr := a.client.Send(payload)
		output := Output{}
		output.Len = len(payload)
		if werr != nil {
			output.Err = werr.Error()
		}
		err = ctx.SetOutputObject(&output)
		ctx.Logger().Info("data sent")
	} else {
		ctx.Logger().Error("no connected")
	}
	return true, err
}
